import { getLinesData, getPieData } from '@/api/modules/electricity'
import type { STORAGE_MODES } from '@/enum/modules/indicator'

export interface PieData {
  name: string
  value: number | null
  unit: string
}
export type PieTitle = string
export interface LineData {
  title: string
  x: string[]
  data: { name: string, unit: string, data: number[] }[]
}

export function useElectricityRateAnalysis() {
  const [pieData1, setPieData1] = useShallowState<PieData[]>([])
  const [pieData2, setPieData2] = useShallowState<PieData[]>([])
  const [pieTitle1, setPieTitle1] = useState<PieTitle>('')
  const [pieTitle2, setPieTitle2] = useState<PieTitle>('')
  const [lineData1, setLineData1] = useShallowState<LineData>({
    x: [],
    title: '',
    data: [],
  })
  const [lineData2, setLineData2] = useShallowState<LineData>({
    x: [],
    title: '',
    data: [],
  })
  const [loading, setLoading] = useState(false)

  async function getAnalyseData(
    pointId: number,
    data: {
      timeType: STORAGE_MODES
      startTime: string
      endTime: string
    },
  ) {
    setLoading(true)
    try {
      let { data: m } = await getPieData(pointId, data)
      let { data: n } = await getLinesData(pointId, data)

      m = m || []
      n = n || []

      setPieData1(m[0]?.data || [])
      setPieData2(m[1]?.data || [])

      setPieTitle1(m[0]?.name || '')
      setPieTitle2(m[1]?.name || '')

      setLineData1({
        x: n[0]?.xaxis?.data || [],
        title: n[0]?.name || '',
        data: n[0]?.series || [],
      })
      setLineData2({
        x: n[1]?.xaxis?.data || [],
        title: n[1]?.name || '',
        data: n[1]?.series || [],
      })
    }
    catch (e) {
      console.warn(e)
    }
    finally {
      setLoading(false)
    }
  }

  return {
    pieData1,
    pieData2,
    pieTitle1,
    pieTitle2,
    lineData1,
    lineData2,
    loading,
    getAnalyseData,
  }
}
